package mo.offer_special;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class L074 {

    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, Comparator.comparingInt(i -> i[0]));
        List<int[]> merged = new ArrayList<>();
        merged.add(intervals[0]);
        for (int i = 1; i < intervals.length; i++) {
            int[] last = merged.get(merged.size()-1);
            int[] cur = intervals[i];
            if (cur[0] > last[1]) {
                merged.add(cur);
            } else if (cur[1] > last[1]) {
                last[1] = cur[1];
            }
        }
        int[][] ret = new int[merged.size()][];
        for (int i = 0; i < merged.size(); i++) {
            ret[i] = merged.get(i);
        }
        return ret;
    }

    public static void main(String[] args) {
        L074 test = new L074();
        System.out.println(Arrays.deepToString(test.merge(new int[][]{{1, 4}, {4, 5}})));
    }

}
